package com.ls.lserp.modules.order.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.order.entity.OperatingP;
import com.ls.lserp.modules.order.entity.QualityResult;
import com.ls.lserp.modules.order.entity.StyleCostEntity;
import com.ls.lserp.modules.order.service.QualityResultService;
import com.ls.lserp.modules.order.service.QuotationService;
import com.ls.lserp.modules.produce.entity.ProduceParameter;
import com.ls.lserp.modules.produce.entity.ProducePlan;
import com.ls.lserp.modules.produce.entity.ProductionLocation;
import com.ls.lserp.modules.produce.service.ProductionLocationService;
import com.ls.lserp.modules.sys.utils.UserUtils;
import com.ls.lserp.modules.trade.entity.BookingOrders;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import groovy.util.ResourceException;



@Controller
@RequestMapping(value = "${adminPath}/quality/result/")
public class QualityResultController extends BaseController {

	
	@Autowired
	private QualityResultService qualityResultService;
	@Autowired
	Configuration freemarkerConfiguration;
	
	@ModelAttribute
	public QualityResult get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return qualityResultService.get(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new QualityResult();
		}
	}

	/**
	 * 跳转页面
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String qualityResult(String date,Model model) {
		// 获取工序信息
        List <OperatingP> operatingPList = qualityResultService.getOperatingPList();
        // 前台select组件使用（工序表）
        model.addAttribute ("operatingPList", operatingPList);
		return "modules/order/qualityResult";
	}
	
	/**
	 * 拼接一览画面
	 * @param values 
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("quality:result:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(QualityResult qualityResult, HttpServletRequest request, HttpServletResponse response,
			Model model, String[] values) throws Exception {
					Map<Object, Object> listMap = new HashMap<Object, Object>();
					// ajax回调时使用的一览list名
					request.setAttribute(Global.LIST_NAME, "qualityResult");

					// 拼接字符串供分页使用
					StringBuilder searchParam = new StringBuilder();
					// 订单号
					searchParam.append("&styleNo=");
					searchParam.append(qualityResult.getStyleNo());
					//交货日期
					searchParam.append("&dateStart=");
					searchParam.append(qualityResult.getDateStart());
					//订单号
					searchParam.append("&orderNO=");
					searchParam.append(qualityResult.getOrderNO());
					//结束日期
					searchParam.append("&tabPageStatus=");
					searchParam.append(qualityResult.getTabPageStatus());
					//排序条件
					searchParam.append("&orderByTerm=");
					searchParam.append(qualityResult.getOrderByTerm());
					//排序类型（升序、降序）
					searchParam.append("&orderByType=");
					searchParam.append(qualityResult.getOrderByType());
					// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
					request.setAttribute(Global.SEARCH_PAEAM, searchParam);
					
					// 查询一览页面数据
					Page<QualityResult> page = qualityResultService.findList(new Page<QualityResult>(request, response),
							qualityResult);
					// 读取系统路径
					String strUri = request.getContextPath() + Global.getAdminPath();
					// 读取文件生成字符串
					String strHtml = "";
					Map<String, Object> map = new HashedMap();
					map.put("adminUri", strUri);
					map.put("qualityResults", page.getList());
					map.put("pageNo", page.getPageNo());
					map.put("pageSize", page.getPageSize());
					map.put("springMacroRequestContext", new RequestContext (request));
					strHtml = FreeMarkerTemplateUtils
							.processTemplateIntoString(freemarkerConfiguration.getTemplate("qualityResult.ftl"), map);
					listMap.put("qualityResult", strHtml);
					listMap.put("page", page.getHtml());

					// ajax返回结果
					return renderString(response, listMap);
		}
	
	
	
	
	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
	
	/**
	 * 进入查看页面
	 * 
	 * @param produceparameter
	 * @param model
	 * @return
	 */
	@RequiresPermissions("quality:result:view")
	@RequestMapping(value = "show")
	public String show(QualityResult qualityResult, HttpServletRequest request, HttpServletResponse response, Model model) {

		List<QualityResult> qualityResultDetailsList = qualityResultService.findDetailsList(qualityResult.getStyleID(),qualityResult.getOperatingID());
    	model.addAttribute("qualityResultDetailsList", qualityResultDetailsList);
		// 返回页面地址
		return "modules/order/qualityResultDeteils";
	}
	
	
	
	
	
	
	
	

	

}